<template>
  <div>
    <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="1024" @ok="handleSubmit">
      <a-tabs v-model:activeKey="activeFormKey" animated @change="handleChangeTabs" type="card">
        <a-tab-pane tab="基本信息" key="formBasicinformation" :forceRender="true">
          <BasicForm @register="registerBasicinformationForm" ref="formBasicinformationRef">
            <template #timeIntervalSlot="{ model, field }">
              <a-input-search :disabled="isDetail" v-model:value="model[field]" readonly placeholder="请选择时格" @search="timeOpen" />
            </template>
          </BasicForm>
        </a-tab-pane>
      </a-tabs>
      <!-- 子表单区域 -->
      <a-tabs v-model:activeKey="activeKey" animated @change="handleChangeTabs">
        <a-tab-pane tab="计划订单" key="psPlanOrderItem" :forceRender="true">
          <vxe-toolbar>
            <template #buttons>
              来源类型：
              <a-select v-model:value="srcType" style="width:140px;" placeholder="请选择来源类型" @change="planMethodChange">
                <a-select-option :value="0">原订单</a-select-option>
                <a-select-option :value="1">总装排产计划</a-select-option>
                <a-select-option :value="2">主生产计划</a-select-option>
              </a-select>
              <a-button color="primary" style="margin-left:5px;" :disabled="isDetail" @click="masterPlanOpen()">新增</a-button>
            </template>
            <template #tools>
              <!-- <a-button color="success" @click="clickDistributePlan"
            v-if="hasPermission('ps:ps_planning_scheduling:distribute')" class="m-4">下发计划</a-button> -->
            </template>
        </vxe-toolbar>
          <JVxeTable
            keep-source
            resizable
            ref="psPlanOrderItem"
            :rowNumber="true"
            rowNumKey="rowNum"
            :loading="psPlanOrderItemTable.loading"
            :columns="psPlanOrderItemTable.columns"
            :dataSource="psPlanOrderItemTable.dataSource"
            :height="340"
          >
            <template #srcDocTypeSlot="props">
             {{ props.row.srcDocType == 0?'源订单':props.row.srcDocType==1?'总装排产计划':'主生产计划' }}
            </template>
            <template #action="props">
              <a-popconfirm title="确定删除吗？" @confirm="handleDelete(props.row)">
                <a>删除</a>
              </a-popconfirm>
            </template>
          </JVxeTable>
        </a-tab-pane>
        <a-tab-pane tab="MRP计算结果" key="psPlanOrderResult" :forceRender="true">
          <JVxeTable
            keep-source
            resizable
            ref="psPlanOrderResult"
            :rowNumber="true"
            rowNumKey="rowNum"
            :loading="psPlanOrderResultTable.loading"
            :columns="psPlanOrderResultTable.columns"
            :dataSource="psPlanOrderResultTable.dataSource"
            :height="340"
            :disabled="formDisabled"
          >
            <template #action="props">
              <a-input-search
                @click="handleView(props, 2)"
                placeholder="请选择料品编码"
                readonly
                :disabled="isDetail"
                v-model:value="props.row.materialCode"
              >
              </a-input-search>
            </template>
          </JVxeTable>
        </a-tab-pane>
        <a-tab-pane tab="日志" key="psPlanOrderLog" :forceRender="true">
          <JVxeTable
            keep-source
            resizable
            ref="psPlanOrderLog"
            :rowNumber="true"
            rowNumKey="rowNum"
            :loading="psPlanOrderLogTable.loading"
            :columns="psPlanOrderLogTable.columns"
            :dataSource="psPlanOrderLogTable.dataSource"
            :height="340"
            :disabled="formDisabled"
          >
            <template #executeStatusSlot="props">
              {{ (props.row.executeStatus == null || props.row.executeStatus == undefined) ?  '运算中' : props.row.executeStatus == 1 ? '成功':'失败'  }}
            </template>
          </JVxeTable>
        </a-tab-pane>
        <!-- <template v-slot:rightExtra> 
          <a-form
            :model="searchFormParams"
            layout="inline"
            name="basic"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 16 }"
            @finish="onSearchTab"
          >
            <a-form-item
              label="销售订单号"
            >
              <a-input v-model:value="searchFormParams.billCode" placeholder="请输入销售订单号" />
            </a-form-item>
            <a-form-item
              label="产品编号"
            >
              <a-input v-model:value="searchFormParams.materialCode" placeholder="请输入产品编号"/>
            </a-form-item>
            <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
              <a-button type="primary" html-type="submit">查询</a-button>
            </a-form-item>
          </a-form>
        </template> -->
      </a-tabs>
      <template #appendFooter v-if="isDetail">
        <a-button @click="handleCalculate">运算</a-button>
      </template>
      <template #centerFooter>
        <a-popconfirm title="编辑之后将会清除原有的MRP运算结果！是否确认编辑?" v-model:visible="visible" @confirm="handleOk"></a-popconfirm>
      </template>
    </BasicModal>
    <!-- MPS主生产计划列表 -->
    <mpsSelectModel @register="mpsItemRegModal" @getSelectResult="mpsItemhandleSuccess" :multiple="true" />
    <!-- 料品 -->
    <materialSelectModel @register="materialRegModal" @getSelectResult="materialhandleSuccess" />
    <!-- 订单选择 -->
    <orderSelectModel @register="orderRegModal" @getSelectResult="orderhandleSuccess" :queryType="0"/>
    <!-- 下发汇总 -->
    <distributeSummaryTable @register="arrangementPlanRegModal" @getSelectResult="arrangementPlanhandleSuccess" :multiple="true" />
    <!-- 时格 -->
    <timeSelectModel @register="timeRegModal" @getSelectResult="timehandleSuccess" />
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, unref, reactive, nextTick } from 'vue';
import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { JVxeTable } from '/@/components/jeecg/JVxeTable';
import { useJvxeMethod } from '/@/hooks/system/useJvxeMethods.ts';
import mpsSelectModel from '/@/views/components/mpsSelectModel.vue';
import arrangementPlansSelectModel from '/@/views/components/arrangementPlansSelectModel.vue';
import { basicinformationFormSchema, psPlanOrderItemColumns, psPlanOrderResultColumns, psPlanOrderLogColumns } from '../PsPlanOrder.data';
import {
  saveOrUpdate,
  psPlanOrderItemList,
  psPlanOrderResultList,
  postMrpCalculate,
  getMpsItemByMainIds,
  psPlanOrderLogList,
  deleteItem
} from '../PsPlanOrder.api';
import { VALIDATE_FAILED } from '/@/utils/common/vxeUtils';
import materialSelectModel from '/@/views/components/materialSelectModel.vue';
import { useLoading } from '/@/components/Loading';
import orderSelectModel from '/@/views/components/orderSelectModel.vue';
import { useMessage } from '/@/hooks/web/useMessage';
import { clickExport } from '/@/utils/fileUtils/index';
// import orderSelectModel from '/@/views/components/orderSelectModel.vue';
import timeSelectModel from '/@/views/components/timeSelectModel.vue';
import distributeSummaryTable from './distributeSummaryTable.vue';
interface Props {
  planId: number | string;
}
const propsData = defineProps<Props>();
const visible = ref<boolean>(false);
// Emits声明
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);
const isDetail = ref(false);
const formDisabled = ref(false);
const refKeys = ref(['psPlanOrderItem', 'psPlanOrderResult', 'psPlanOrderLog']);
const activeKey = ref('psPlanOrderItem');
const activeFormKey = ref('formBasicinformation');
const psPlanOrderItem = ref();
const psPlanOrderResult = ref();
const psPlanOrderLog = ref();
// 判断去重的数组
let deWeightArr = reactive([]);
let tempTableArr = reactive([]);
const $message = useMessage();
const tableRefs = { psPlanOrderItem, psPlanOrderResult, psPlanOrderLog };
const activeTable = reactive({
  index: 0,
  refTab: null,
});
const srcType = ref<number>(0)
// 计划订单  列表
const psPlanOrderItemTable = reactive({
  loading: false,
  dataSource: <any[]>[],
  columns: psPlanOrderItemColumns,
});
// 计划订单  查询参数
const searchFormParams = reactive({
  billCode: '',
  materialCode: '',
});
// 计划订单  结果
const psPlanOrderResultTable = reactive({
  loading: false,
  dataSource: [],
  columns: psPlanOrderResultColumns,
});
// 计划订单  日志
const psPlanOrderLogTable = reactive({
  loading: false,
  dataSource: [],
  columns: psPlanOrderLogColumns,
});
// 基本信息表单配置
const [
  registerBasicinformationForm,
  {
    resetFields: resetFieldsBasicinform,
    setProps: setPropsBasicinform,
    validate,
    setFieldsValue: setFieldsBasicinformValue,
    getFieldsValue: getFieldsValueBasicinform,
    updateSchema: updateSchemaBasicinform,
  },
] = useForm({
  labelWidth: 120,
  schemas: basicinformationFormSchema,
  showActionButtonGroup: false,
  baseColProps: {
    span: 8,
  },
});
const [openFullLoading, closeFullLoading] = useLoading({
  tip: '运算中...',
});
const planOrderId = ref<string|null>(null)
//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  console.log('isUpdate...............', data)
  
  //重置表单
  await reset();
  setModalProps({
    confirmLoading: false,
    showCancelBtn: data?.showFooter,
    showOkBtn: data?.showFooter,
  });
  isUpdate.value = !!data?.isUpdate;
  isDetail.value = !!data?.isDetail;
  formDisabled.value = !data?.showFooter;
  if (unref(isUpdate)) {
    planOrderId.value = data.record.id
    //表单赋值
    await setFieldsBasicinformValue({
      ...data.record,
    });
    // 获取计划订单数据
    requestSubTableData(
      psPlanOrderItemList,
      {
        id: data?.record?.id,
      },
      psPlanOrderItemTable
    );
    // 获取计划订单 mrp计算结果列表数据
    requestSubTableData(
      psPlanOrderResultList,
      {
        id: data?.record?.id,
      },
      psPlanOrderResultTable
    );
    requestSubTableData(
      psPlanOrderLogList,
      {
        id: data?.record?.id,
      },
      psPlanOrderLogTable
    );
  }
  // 隐藏底部时禁用整个表单;
  setPropsBasicinform({
    disabled: !data?.showFooter,
  });
});
//方法配置
const [handleChangeTabs, handleSubmit, requestSubTableData, formBasicinformationRef] = useJvxeMethod(
  requestAddOrEdit,
  classifyIntoFormData,
  tableRefs,
  activeKey,
  refKeys
);

//设置标题
const title = computed(() => (unref(isDetail) ? '详情' : !unref(isUpdate) ? '新增' : '编辑'));
// 注册mps筛选框
const [mpsItemRegModal, { openModal: openMpsListModal }] = useModal();
const [orderRegModal, { openModal: openOrderListModal }] = useModal();
const [materialRegModal, { openModal: openMaterialModal }] = useModal();
const [arrangementPlanRegModal, { openModal: openArrangementPlanModal }] = useModal();
const [timeRegModal, { openModal: openTimeModal }] = useModal();
// 重置表单
async function reset() {
  await resetFieldsBasicinform();
  activeKey.value = 'psPlanOrderItem';
  activeFormKey.value = 'formBasicinformation';
  psPlanOrderItemTable.dataSource = [];
  psPlanOrderResultTable.dataSource = [];
}
function classifyIntoFormData(allValues) {
  let main = Object.assign({}, allValues.formValue);
  allValues.tablesValue[0].tableData.forEach((item) => {
    deWeightArr.push(item.billCode + item.orderRowNum);
  });
  return {
    ...main, // 展开
    psPlanOrderItemList: allValues.tablesValue[0].tableData,
    psPlanOrderResultList: allValues.tablesValue[1].tableData,
    psPlanOrderLogList: allValues.tablesValue[2].tableData,
  };
}
// 查询计划订单列表
function onSearchTab() {
  let formData = getFieldsValueBasicinform();
  searchFormParams.id = formData?.id;
}
// 切换来源类型 清空原有的数据
function planMethodChange(e) {
  console.log(e)
}

function masterPlanOpen() {
  switch (srcType.value) {
    case 0:
      openOrderListModal(true, {
        isUpdate: false,
        showFooter: true,
      });
      break;
    case 1:
      openArrangementPlanModal(true, {
        isUpdate: false,
        showFooter: true,
      });
      break;
    case 2:
      openMpsListModal(true, {
        isUpdate: false,
        showFooter: true,
      });
      break;
    default:
      $message.createMessage.warn('请先选择来源类型');
      break;
  }
}
//时隔
function timeOpen() {
  openTimeModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//时格回写
function timehandleSuccess(val, values) {
  setFieldsBasicinformValue({
    timeIntervalName: val[0].label,
    timeIntervalId: val[0].value,
  });
}

//  mrp运算
function handleCalculate(record) {
  openFullLoading();
  // 延时调用  避免数据量少时遮罩一闪而过
  setTimeout(() => {
    postMrpCalculate({
      id: propsData.planId,
    })
      .then((res) => {
        // closeFullLoading();
      })
      .finally((err) => {
        closeFullLoading();
      });
  }, 500);
}

// mps筛选回写
function mpsItemhandleSuccess(val, values) {
  getMpsDetail(ids);
}
// 获取Mps详情
async function getMpsDetail(ids) {
  let res = await getMpsItemByMainIds({
    ids: ids,
  });
  psPlanOrderItemTable.dataSource = psPlanOrderItem.value!.getTableData();
  res.map((item, idx) => {
    item.orderRowNum = item.rowNum;
    item.rowNum = (idx + 1) * 10;
    delete item.id;
    psPlanOrderItemTable.dataSource.push(item);
  });
  // psPlanOrderItemTable.dataSource = res;
}
//打开选择料品
function handleView(props, refTab) {
  activeTable.index = props.params.$rowIndex;
  activeTable.refTab = refTab;
  openMaterialModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}

//料品回写
function materialhandleSuccess(val, values) {
  let index = activeTable.index;
  let refTab = activeTable.refTab == 1 ? psPlanOrderItem : activeTable.refTab == 2 ? psPlanOrderResult : null;
  let table = activeTable.refTab == 1 ? psPlanOrderItemTable : activeTable.refTab == 2 ? psPlanOrderResultTable : null;

  table.dataSource = refTab.value!.getTableData();
  table.dataSource[index].materialName = val[0].label;
  table.dataSource[index].materialId = val[0].value;
  table.dataSource[index].materialCode = val[0].item.code;
  table.dataSource[index].spec = val[0].item.spec;
  // 自动带出单位
  table.dataSource[index].unitId = val[0].item.stockUnitId;
  table.dataSource[index].unitName = val[0].item.stockUnitName;
}
// 根据id删除一条子表
async function handleDelete(row) {
  psPlanOrderItemTable.dataSource = psPlanOrderItem.value!.getTableData();
  const index = psPlanOrderItemTable.dataSource.findIndex(x=>x.srcDocId == row.srcDocId)
  psPlanOrderItemTable.dataSource.splice(index, 1)
//  await deleteItem(id,()=>{
//   if(planOrderId){
//     requestSubTableData(
//       psPlanOrderItemList,
//       {
//         id: planOrderId.value
//       },
//       psPlanOrderItemTable
//     );
//   }
//  })
}
//订单回写
function orderhandleSuccess(val, values, type) {
  psPlanOrderItemTable.dataSource = psPlanOrderItem.value!.getTableData();
  for(let i=0;i<val.length;i++) {
    const v:any = val[i]
    const matchs = psPlanOrderItemTable.dataSource.filter(x=>x.orderNumber == v.item.billCode && x.orderRowNumber == v.item.rowNum)

    if(matchs && matchs.length > 0) continue;
    let orderItem = {
      ...v.item,
      srcDocType: srcType.value,
      srcDocId: v.item.id,
      srcDocRowNo: v.item.rowNum,
      orderNumber: v.item.billCode,
      orderRowNumber: v.item.rowNum
    };

    psPlanOrderItemTable.dataSource.push(orderItem);
  }

}
// 总装排产计划回写
function arrangementPlanhandleSuccess(val, values, type) {
  let ids = values.toString();
  let tempData = [];
  psPlanOrderItemTable.dataSource = psPlanOrderItem.value!.getTableData();
  val.forEach((v, idx) => {
    v.item.billCode = v.item.orderNumber;
    v.item.rowNum = (idx + 1) * 10;
    v.item.billTypeName = '总装排产';
    // 说拿上线日期
    v.item.orderDeliveryDate = v.item.lineDate;
    v.item.orderQuantity = v.item.totalQuantity;

    // tempData.push(v.item);
    psPlanOrderItemTable.dataSource.push(v.item);
  });
}
let formValues = ref(null);
//表单提交事件
async function requestAddOrEdit(values) {

  //新增界面不要提示
  let formData = getFieldsValueBasicinform();

  if (formData.id) {
    visible.value = true;
  }
  try {
    // 校验表单
    const flog = await validate();
    setModalProps({
      confirmLoading: true,
    });
    // 处理表格生成的id : row_***
    values.psPlanOrderItemList.map((item) => delete item.id);
    values.psPlanOrderResultList.map((item) => delete item.id);
    // 获取基础信息表单数据
    let basicinformData = getFieldsValueBasicinform();
    // 合并数据
    formValues = Object.assign({}, values, basicinformData);
    if (!formData.id) {
      //提交表单
      await saveOrUpdate(formValues, isUpdate.value);
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success');
      visible.value = false;
    }
  } finally {
    setModalProps({
      confirmLoading: false,
    });
  }
}
async function handleOk(e: MouseEvent) {
  //提交表单
  await saveOrUpdate(formValues, isUpdate.value);
  //关闭弹窗
  closeModal();
  //刷新列表
  emit('success');
  visible.value = false;
}
</script>

<style lang="less" scoped>
/** 时间和数字输入框样式 */
:deep(.ant-input-number) {
  width: 100%;
}

:deep(.ant-calendar-picker) {
  width: 100%;
}

:deep(.ant-spin-spinning) {
  position: absolute;
  top: 45%;
  left: 45%;
  z-index: 1002;
}
</style>
